package com.hnu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnu.common.Constants;
import com.hnu.entity.Category;
import com.hnu.mapper.ProductMapper;
import com.hnu.service.CategoryService;
import com.hnu.mapper.CategoryMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;

    @SneakyThrows
    @Override
    public int delete(long id) {
        //分类下由商品的不能删除
        Category categoryRoot = categoryMapper.selectById(id);
        QueryWrapper qw = new QueryWrapper();
        qw.eq("category_parent_id",id);
        List<Category> categoryList = categoryMapper.selectList(qw);
        List<Long> ids = categoryList.stream().map(category -> category.getId()).collect(Collectors.toList());
        List<Long> ids1 = new ArrayList<>();
        if (categoryRoot.getGrade() == 1){
            if (categoryList != null && categoryList.size()>0){
                QueryWrapper qw1 = new QueryWrapper();
                qw1.in(ids);
                ids1 = categoryMapper.selectList1(ids);
            }
        }
        ids.add(id);
        ids.addAll(ids1);
        //判断该分类下是否有商品存在
        int count = productMapper.findCountByCIds(ids);
        if (count !=0 ){
            return 0;
        }
        //可以删除
        return  categoryMapper.deleteBatchIds(ids);
    }
}




